package com.vq.service;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.vq.util.EmailUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <h2>存取验证码</h2>
 */
@Service
public class CaptchaService {
    Random random = new Random();
    /**
     * 前缀:Captcha_；过期时间:2；时间单位:分；储存位置:本地；
     */
    @CreateCache(name = "Captcha_", expire = 2, timeUnit = TimeUnit.MINUTES, cacheType = CacheType.LOCAL)
    private Cache<String, String> jetCache;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    EmailUtil emailUtil;
    //发送人
    String from = "vq202306@163.com(VQ官方邮箱)";
    //标题
    String subject = "验证码";

    /**
     * 获取随机验证码
     * @return
     */
    private String getCaptcha() {
        StringBuilder str = new StringBuilder();
        //生成随机六位0到9的数字
        for (int i = 0; i < 6; i++) {
            str.append(String.valueOf(random.nextInt(10)));
        }
        return str.toString();
    }
    /**
     * 生成并发送验证码
     * @param prefix 前缀
     * @param email 电子邮箱
     * @return
     */
    public String sendCaptcha(String prefix, String email) throws MessagingException {
        //判断电子邮箱是否符合格式
        if (!"com".equals(email.substring(email.length()-3))) return null;
        //获取随机验证码
        String code = getCaptcha();
        //生成消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject(subject);
        message.setText("<div style='font-size: 50px'>"+code);
        //发送消息
        emailUtil.send(message, true);
        //向缓存添加
        //jetCache.put(prefix+"_"+email, code);
        // 向缓存添加，并且2分钟过期
        redisTemplate.opsForValue().set(prefix+"_"+email, code, 2, TimeUnit.MINUTES);
        return code;
    }
    /**
     * 判断该验证码是否正确
     * @param prefix 前缀
     * @param email 电子邮箱
     * @param captcha 验证码
     * @return
     */
    public boolean comparisonCaptcha(String prefix, String email, String captcha) {
        if (captcha==null) return false;
        //return captcha.equals(jetCache.get(prefix+"_"+email));
        // 取出值
        String value = redisTemplate.opsForValue().get(prefix+"_"+email);
        // 值相同，删除键值对，返回true。否则返回false,不删除键值对。
        if (captcha.equals(value)) {
            redisTemplate.delete(prefix+"_"+email);
            return true;
        } else return false;
    }
}
